package cn.yuanqiao.archive.common.util;

import cn.yuanqiao.archive.formManage.domain.YqformManage;
import cn.yuanqiao.archive.formManage.formRule.domain.YqFormRule;
import cn.yuanqiao.archive.formManage.formRule.service.IYqFormRuleService;
import cn.yuanqiao.archive.formManage.service.IYqformManageService;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.el.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SplitArchiveList
 * @Description: 类的描述
 * @author: lihuahua
 * @date: 2023/7/6 16:09
 * @Blog: huahuacoco.top
 */

@Component
public class SplitArchiveList {

    @Autowired
    private IYqFormRuleService yqFormRuleService;

    @Autowired
    private IYqformManageService yqformManageService;

    /**
     * 根据表单Code分割档案数据
     * @param formCode 表单code
     * @param archiveList 档案list
     * @return
     */
    /*public static List<List<HashMap<String,Object>>> splitArchiveByFormCode(String formCode,List<HashMap<String,Object>> archiveList){
        List<YqFormRule> yqFormRules = yqFormRuleService.selectYqFormRuleListByFormCode(formCode);

        return null;
    }*/

    public List<List<Map<String, Object>>> splitArchiveByFormCode(String formCode, List<Map<String, Object>> archiveList) {

        List<YqFormRule> yqFormRules = yqFormRuleService.selectYqFormRuleListByFormCode(formCode,SecurityUtils.getTenantCode());

        List<List<Map<String, Object>>> result = new ArrayList<>();
        List<Map<String, Object>> currentGroup = null;

        ExpressionFactory factory = ExpressionFactory.newInstance();
        StandardELContext context = new StandardELContext(factory);
        List<Map<String, Object>> notConditionList = new ArrayList<>();

        for (Map<String, Object> archive : archiveList) {
            boolean matched = false;

            for (YqFormRule rule : yqFormRules) {
                String columnCondition = rule.getColumnCondition();

                // 创建一个变量映射器，用于存储 EL 表达式中的变量值
                VariableMapper variableMapper = context.getVariableMapper();
                for (Map.Entry<String, Object> entry : archive.entrySet()) {
                    variableMapper.setVariable(entry.getKey(), factory.createValueExpression(entry.getValue(), Object.class));
                }

                // 解析并执行 EL 表达式
                ValueExpression expression = factory.createValueExpression(context, columnCondition, Boolean.class);
                Boolean match = (Boolean) expression.getValue(context);

                if (match != null && match) {
                    matched = true;
                    break; // Stop checking other rules once a match is found
                }
            }

            if (matched) {
                if (currentGroup == null) {
                    currentGroup = new ArrayList<>();
                }
                currentGroup.add(archive);
            } else {
                // No match found for the current archive, start a new group
                notConditionList.add(archive);
                if (currentGroup != null) {
                    result.add(currentGroup);
                    currentGroup = null;
                }
            }
            System.out.println(matched);
            System.out.println(archive.toString());
            System.out.println(111);
        }

        // Add the last group if it exists
        if (currentGroup != null) {
            result.add(currentGroup);
            result.add(notConditionList);
        }

        return result;
    }

    public Map<String,Map<String, Object>> splitArchiveByFormCodeNew(String formCode, List<Map<String, Object>> archiveList) {

        List<YqFormRule> yqFormRules = yqFormRuleService.selectYqFormRuleListByFormCode(formCode,SecurityUtils.getTenantCode());

        YqformManage yqformManage = new YqformManage();
        yqformManage.setFormCode(formCode);
        boolean splitFlage = false;
        List<YqformManage> yqformManages = yqformManageService.selectYqformManageList(yqformManage);
        if (yqformManages.size()!=0&&yqformManages.get(0).getIsSplit()!=null&&yqformManages.get(0).getIsSplit().equals("1")){
            //根据GDCS_ID分单标识
            splitFlage = true;
        }

        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> currentGroup = null;

        ExpressionFactory factory = ExpressionFactory.newInstance();
        StandardELContext context = new StandardELContext(factory);
        List<Map<String, Object>> notConditionList = new ArrayList<>();

        //List<Map<String, Object>> matchedArchives = new ArrayList<>();
        Map<String, Object> matchedFields = new HashMap<>();
        //放置已经匹配的数据
        Map<String,Map<String, Object>> matchedCondMapAll = new HashMap<>();
        //循环档案数据
        for (Map<String, Object> archive : archiveList) {
            boolean matched = false;

            String columnConditionAll = null;

            String columnCondition = null;

            //循环规则
            for (YqFormRule rule : yqFormRules) {
                columnCondition = rule.getColumnCondition();

                //获取规则的详情
                List<YqFormRule> yqFormRuleItem = yqFormRuleService.selectYqFormRuleByGroupId(rule.getRuleId());
                // 创建一个变量映射器，用于存储 EL 表达式中的变量值
                VariableMapper variableMapper = context.getVariableMapper();
                for (Map.Entry<String, Object> entry : archive.entrySet()) {
                    variableMapper.setVariable(entry.getKey(), factory.createValueExpression(entry.getValue(), Object.class));
                }

                // 解析并执行 EL 表达式
                ValueExpression expression = factory.createValueExpression(context, columnCondition, Boolean.class);
                Boolean match = false;
                try {
                    //获取el表达式结果
                     match = (Boolean) expression.getValue(context);
                }catch (PropertyNotFoundException e){
                    System.out.println("尝试获取不存在字段："+e.getMessage());
                    //控制台日志提醒,如果是非标准的字段尝试从下面方法获取额外字段
                    setVariablesNotHas(yqFormRuleItem,variableMapper,factory,context);
                    expression = factory.createValueExpression(context, columnCondition, Boolean.class);
                    match = (Boolean) expression.getValue(context);
                }

                if (match != null && match) {
                    if (columnConditionAll==null){
                        String gdcsId = splitFlage?archive.get("GDCS_ID")+"&&&":"";
                        columnConditionAll = gdcsId + columnCondition;
                    }else {
                        columnConditionAll = columnConditionAll+"&&&"+columnCondition;
                    }
                    matched = true;
                    //给档案数据添加上符合条件的字段
                    for (YqFormRule item:yqFormRuleItem) {
                        String fieldName = item.getFieldName();
                        String fieldValue = String.valueOf(variableMapper.resolveVariable(fieldName).getValue(context));
                        if (fieldValue!=null&&!fieldValue.equals("")&&!fieldValue.equals("null")){
                            matchedFields.put(fieldName, fieldValue);
                        }
                    }
                    //break; // Stop checking other rules once a match is found
                }
            }

            if (matched) {
                if (currentGroup == null) {
                    currentGroup = new ArrayList<>();
                }
                currentGroup.add(archive);
                matchedFields.put("archiveData",currentGroup);

                if (matchedCondMapAll.get(columnConditionAll)==null){
                    matchedCondMapAll.put(columnConditionAll,matchedFields);
                    matchedFields = new HashMap<>();
                }else {
                    List<Map<String, Object>> archiveData = (List<Map<String, Object>>) matchedCondMapAll.get(columnConditionAll).get("archiveData");
                    archiveData.add(archive);
                }
                currentGroup = new ArrayList<>();
            } else {
                // No match found for the current archive, start a new group
                notConditionList.add(archive);
                if (currentGroup != null) {
                    //Map condition = new HashMap<String,Object>();
                    matchedFields.put("archiveData",currentGroup);
                    result.add(matchedFields);
                    currentGroup = null;
                    matchedFields = new HashMap<>();
                }
            }
        }
        Map<String,Object> map = new HashMap();
        map.put("archiveData",notConditionList);
        matchedCondMapAll.put("notConditionValue",map);

        if (yqFormRules.size()==0){
            Map<String,Object> maps = new HashMap();
            maps.put("archiveData",archiveList);
            matchedCondMapAll.put("allArchiveData",maps);
        }

        return matchedCondMapAll;
    }

    private void setVariablesNotHas(List<YqFormRule> yqFormRuleItem, VariableMapper variableMapper, ExpressionFactory factory,StandardELContext context) {
        for (YqFormRule itemRule : yqFormRuleItem) {
            String fieldName = itemRule.getFieldName();
            //ValueExpression valueExpression = variableMapper.resolveVariable(fieldName);
            if ("archive_type".equals(fieldName)){
                String type = String.valueOf(variableMapper.resolveVariable("TYPE").getValue(context));
                if ("WS".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("wsda", Object.class));
                }else if ("KY".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("kyda", Object.class));
                }else if ("GC".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("gcwj", Object.class));
                }else if ("LT".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("lt", Object.class));
                }else if ("DZDT".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("dzdt", Object.class));
                }else if ("STDT".equals(type)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("stdt", Object.class));
                }else {
                    variableMapper.setVariable(fieldName, factory.createValueExpression("qtda", Object.class));
                }
            }else if ("archive_has_mj".equals(fieldName)){
                String mj = String.valueOf(variableMapper.resolveVariable("MJ").getValue(context));
                if (mj == null||"null".equals(mj)||"".equals(mj)||"0".equals(mj)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("0", Object.class));
                }else {
                    variableMapper.setVariable(fieldName, factory.createValueExpression("1", Object.class));
                }
            }else if ("archive_is_dept".equals(fieldName)){
                String deptId = String.valueOf(variableMapper.resolveVariable("GDCS_ID").getValue(context));
                String userDeptId = String.valueOf(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                if (userDeptId.equals(deptId)){
                    variableMapper.setVariable(fieldName, factory.createValueExpression("1", Object.class));
                }else {
                    variableMapper.setVariable(fieldName, factory.createValueExpression("0", Object.class));
                }
            }
        }
    }


}

